package com.superfish.cutieshop.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.superfish.cutieshop.BaseActivity;
import com.superfish.cutieshop.BaseApp;
import com.superfish.cutieshop.BaseConfig;
import com.superfish.cutieshop.R;
import com.superfish.cutieshop.adapter.MainAdapter;
import com.superfish.cutieshop.been.Notify;
import com.superfish.cutieshop.been.PhaseDetail;
import com.superfish.cutieshop.been.ShopItem;
import com.superfish.cutieshop.been.Version;
import com.superfish.cutieshop.dialog.AppDialog;
import com.superfish.cutieshop.dialog.BaseDialog;
import com.superfish.cutieshop.http.HttpError;
import com.superfish.cutieshop.http.HttpStores;
import com.superfish.cutieshop.http.ZokeParams;
import com.superfish.cutieshop.parser.GsonMain;
import com.superfish.cutieshop.parser.GsonPhase;
import com.superfish.cutieshop.parser.GsonVersion;
import com.superfish.cutieshop.service.MyPushIntentService;
import com.superfish.cutieshop.service.NewPushIntentService;
import com.superfish.cutieshop.utils.CommonUtil;
import com.superfish.cutieshop.utils.CutieToast;
import com.superfish.cutieshop.utils.DownloadVersionApk;
import com.superfish.cutieshop.utils.DownloadVersionListener;
import com.superfish.cutieshop.utils.HttpParams;
import com.superfish.cutieshop.utils.LogTest;
import com.superfish.cutieshop.utils.PersistTool;
import com.superfish.cutieshop.utils.TimeUtils;
import com.superfish.cutieshop.view.XListView;
import com.umeng.message.PushAgent;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.sharesdk.framework.ShareSDK;

/**
 * 设置透明Header 背景增加图 不变的图
 **/
@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity implements XListView.IXListViewListener {


    public static void open(Activity act) {
        Intent intent = new Intent(act, MainActivity.class);
        open(act, intent);
    }

    public static final int COUNT = 20;
    private int mPage = 0;
    @ViewInject(R.id.xListView)
    private XListView mListView;
    private MainAdapter mAdapter;
    private List<ShopItem> mList = new ArrayList<>();
    private boolean hasMore = true;
    private String mTime;
    @ViewInject(R.id.mb)
    private ImageView mMbIv;
    @ViewInject(R.id.gm_word)
    private ImageView mGmword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ShareSDK.initSDK(this);
        initUMengMessage();
        View mHeadView = getLayoutInflater().inflate(R.layout.view_header, null);
        mListView.addHeaderView(mHeadView);
        mListView.setPullRefreshEnable(false);
        mListView.setPullLoadEnable(true);
        mListView.setXListViewListener(this);
        //设置蒙版渲染色
        mEnableDoubleExit = true;
        mAdapter = new MainAdapter(this, mList);
        mListView.setAdapter(mAdapter);
        TextView moreTv = mListView.getLoadMoreTextView();
        moreTv.setTextColor(getResources().getColor(R.color.y0));
        if (android.os.Build.VERSION.SDK_INT > 8) {// 判断sdk版本
            mListView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        } else {
            mListView.setFadingEdgeLength(0);
        }
        mPage = 0;
        showLoading();
        fetchMainList(mPage);
        fetchVersion();
    }


    /**
     * 加载首页接口
     **/
    private void fetchMainList(int page) {
        ZokeParams params = HttpParams.getMainListV1(mHashCode, COUNT, page, mTime);
        HttpParams.logParams(params);
        HttpStores.getInstense().get(params);
    }

    /**
     * 版本检测
     **/
    private void fetchVersion() {
        ZokeParams params = HttpParams.getDefaultByGet(BaseConfig.UrlBank.version, mHashCode);
        HttpStores.getInstense().get(params);
    }

    @Override
    public void onSuccess(ZokeParams out) {
        super.onSuccess(out);
        ResponseInfo info = (ResponseInfo) out.getResult();
        String result = (String) info.result;
        LogTest.wlj("result=" + result);
        String url = out.getUrl();
        if (url.equals(BaseConfig.UrlBank.mainList_v1)) {
            GsonMain gm = new GsonMain().fromJson(result);
            if (gm.info == null || gm.error_code != 0) {
                mListView.stopRefresh();
                mListView.stopLoadMore();
                hasMore = true;
                if (mPage != 0) {
                    mPage--;
                }
                // 提示网络不给力
                if (mList.size() == 0) {
                    showNetFail();
                } else {
                    CutieToast.showNetFailed(getApplicationContext());
                }
                return;
            }
            //判断是否有下一页
            hasMore = gm.info.next_page == 1;//true 存在下一页
            mListView.setPullLoadEnable(gm.info.next_page == 1);
            if (mPage == 0) {
                mList.clear();
            }
            //
            ShopItem[] list = gm.info.list;
            if (list != null && list.length != 0) {
                for (ShopItem item : list) {
                    mList.add(item);
                }
            }
            if (mPage == 0 && gm.info.list.length != 0) {
                ShopItem im = mList.get(0);
                mTime = im.online_time + "";
                mMbIv.setBackgroundResource(TimeUtils.getMbRes(im.online_time * 1000));
                //支持
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    mMbIv.setAlpha(0.5f);
                    mGmword.setAlpha(0.9f);
                }
            }
            showContent();
            mAdapter.notifyDataSetChanged();
            mListView.stopRefresh();
            mListView.stopLoadMore();

            return;
        }


        if (url.equals(BaseConfig.UrlBank.version)) {
            GsonVersion gv = new GsonVersion().fromJson(result);
            if (gv.info == null || gv.error_code != 0) {
                return;
            }
            checkCode(gv.info);
            return;
        }

        if (url.equals(BaseConfig.UrlBank.phases)) {
            //快捷回复列表
            GsonPhase gp = new GsonPhase().fromJson(result);
            if (gp.info == null || gp.info.length == 0 || gp.error_code != 0) {
                return;
            }
            //使用简单存储--缓存
            PersistTool.saveString(BaseConfig.UrlBank.phases, result);
            return;
        }
    }

    @Override
    public void onFails(ZokeParams out) {
        super.onFails(out);
        HttpError error = (HttpError) out.getResult();
        LogTest.wlj("error=" + error.s + ":" + error.exception.getExceptionCode());
        String url = out.getUrl();
        if (url.equals(BaseConfig.UrlBank.mainList_v1)) {
            mListView.stopRefresh();
            mListView.stopLoadMore();
            if (mPage != 0) {
                mPage--;
            }
            CutieToast.showNetFailed(getApplicationContext());
            return;
        }
    }


    private void checkCode(final Version vs) {
        try {
            if (vs == null)
                return;
            int serverCode = vs.ver;
            int clientCode = CommonUtil
                    .getClientVersionCode(getApplicationContext());
            boolean isForce = vs.status == 1;
            if (clientCode < serverCode) {
                if (isForce) {
                    // 强制更新
                    showForceDialog(vs);
                    return;
                }
                // 如果用户忽略过一次 则不再提示弹框
                int perCode = PersistTool.getInt(BaseConfig.ShareKey.VERSIONCHECKKEY, -1);
                if (perCode == serverCode)
                    return;
                // 非强制更新 --记录下用户的操作
                showNorDialog(vs);
                return;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行home操作
     **/
    private void intoHome() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }


    /**
     * 弹出非强制更新框
     **/
    private void showNorDialog(final Version vs) {
        final AppDialog mNorDialog = new AppDialog(MainActivity.this);
        String str = getResources().getString(R.string.versionDownloadtitle);
        str = String.format(str, "" + vs.name);
        mNorDialog.setDialogTitle(str);
        mNorDialog.setSubTitle(vs.describe);
//        mNorDialog.setContent(vs.describe);
        mNorDialog.setLeftClick(new BaseDialog.LeftClickLinstener() {
            @Override
            public void onClickLeft(View view) {
                // 忽略 -- 只提示用户一次
                PersistTool.saveInt(BaseConfig.ShareKey.VERSIONCHECKKEY, vs.ver);
                mNorDialog.dismiss();
            }
        });
        //
        mNorDialog.setRightClick(new BaseDialog.RightClickLinstener() {
            @Override
            public void onClickRight(View view) {
                downloadApk(vs.url);
                mNorDialog.dismiss();
            }
        });
        // --
        mNorDialog.setLeftText(getResources().getString(
                R.string.versionDownloadcancle));
        mNorDialog.setRightText(getResources().getString(
                R.string.versionDownload));
        mNorDialog.show();
    }


    /**
     * 弹出强制更新框
     **/
    private void showForceDialog(final Version vs) {
        final AppDialog mForce = new AppDialog(MainActivity.this);
        mForce.setCancelabled(false);// 强制更新不能取消弹框
        String str = getResources().getString(R.string.versionDownloadtitle);
        str = String.format(str, "" + vs.name);
        mForce.setDialogTitle(str);
        mForce.setSubTitle(vs.describe);
//        mForce.setContent(vs.describe);
        mForce.setLeftText(getResources().getString(
                R.string.versionDownloadedit));
        mForce.setRightText(getResources().getString(R.string.versionDownload));
        mForce.setLeftClick(new BaseDialog.LeftClickLinstener() {
            @Override
            public void onClickLeft(View view) {
                // 退出应用
                BaseApp app = (BaseApp) getApplicationContext();
                app.exitApp();
                intoHome();
            }
        });
        // --
        mForce.setRightClick(new BaseDialog.RightClickLinstener() {
            @Override
            public void onClickRight(View view) {
                downloadApk(vs.url);
                // 执行程序Home
                intoHome();
            }
        });
        // 记住用户忽略的版本号 弹出时是否进行提示
        mForce.show();
    }

    private void downloadApk(String url) {
        // 防止重复下载
        if (!DownloadVersionApk.getInstense(MainActivity.this).isdoing) {
            DownloadVersionApk.getInstense(MainActivity.this).downLoad(url);
            DownloadVersionApk.getInstense(MainActivity.this).setListener(
                    new DownloadVersionListener() {
                        @Override
                        public void onSuccess(File file) {
                            // 下载完 执行安装
                            CommonUtil
                                    .installApk(file, getApplicationContext());
                        }
                    });
        } else {
            // 提示下
            CutieToast.show(getApplicationContext(), R.string.versionCheckedToast);
        }

    }


    public void showLoading() {
        mPageState.showLoading();
        mListView.setVisibility(View.GONE);
    }

    public void showNetFail() {
        mPageState.showNetFailed();
        mListView.setVisibility(View.GONE);
        mPageState.setOnReloadListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPage = 0;
                showLoading();
                fetchMainList(mPage);
            }
        });
    }

    public void showContent() {
        mPageState.hide();
        mListView.setVisibility(View.VISIBLE);

    }

    @Override
    public void onRefresh() {
        mPage = 0;
        fetchMainList(mPage);
    }

    @OnClick(R.id.userIv)
    public void onClickUser(View v) {
        UserProfileActivity.open(this);
//        TestLoadingActivity.open(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onLoadMore() {
        if (!hasMore) {
            mListView.stopRefresh();
            mListView.stopLoadMore();
            CutieToast.showNoMore(getApplicationContext());
            return;
        }
        mPage++;
        fetchMainList(mPage);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        ShopItem s = (ShopItem) intent.getSerializableExtra(BaseConfig.INTENT_SHOPITEM);
        if (s != null) {
            PhaseDetailActivity.open(this, "" + s.tid, s.title, s.subtitle, s.cover);
        }
    }

    /**
     * 初始化友盟消息
     */
    private void initUMengMessage() {
        final PushAgent mPushAgent = PushAgent.getInstance(this);
        mPushAgent.enable();
        mPushAgent.setPushIntentServiceClass(NewPushIntentService.class);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @OnClick(R.id.icon)
    public void onClickIcon(View v) {
        CutieToast.show(this, "呀买碟，内容马上就来");
        mPage = 0;
        fetchMainList(mPage);
    }
}
